package com.aduerr.v1shouyin.unioncard;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.common.Constants;
import com.aduerr.v1shouyin.mvp.adpter.UnionTranscationAdapter;
import com.aduerr.v1shouyin.util.ToastUtils;
import com.orhanobut.hawk.Hawk;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.yeahka.shouyintong.sdk.action.PosSign;
import com.yeahka.shouyintong.sdk.action.TransQueryList;
import com.yeahka.shouyintong.sdk.api.SytApi;
import com.yeahka.shouyintong.sdk.api.SytFactory;
import com.yeahka.shouyintong.sdk.excep.ActionIllegalException;
import com.yeahka.shouyintong.sdk.info.TradeInfo;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author HI
 * @email dev1024@foxmail.com
 * @time 2019/7/17 15:01
 * @change
 * @chang time
 * @class describe
 */

public class UnionTranscationRecordActivity extends BaseUnionActivity {

    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.rl_no_data)
    RelativeLayout rlNoData;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.et_reference_no)
    EditText etReferenceNo;


    private UnionTranscationAdapter unionTranscationAdapter;

    private SytApi sytApi;
    private int curPage = 1;

    BroadcastReceiver broadcastReceive = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(TextUtils.equals(action, Constants.ACTION)) {
                try {
                    sytApi.handleAction(intent, baseResp -> {
                        if(baseResp.isSuccessful()) {
                            if(baseResp instanceof PosSign.Resp) {
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                Hawk.put("signTime", sdf.format(new Date()));
                                Hawk.put("unionMerchantId",
                                        ((PosSign.Resp) baseResp).merchantId);
                                //签到
                                Intent intentSign =
                                        new Intent(UnionTranscationRecordActivity.this,
                                                UnionSignInActivity.class);
                                intentSign.putExtra("resp", baseResp);
                                startActivity(intentSign);
                            } else if(baseResp instanceof TransQueryList.Resp) {
                                //列表
                                initData(((TransQueryList.Resp) baseResp).tradeInfoList);
                            }
                        } else {
                            if(baseResp instanceof PosSign.Resp || baseResp instanceof TransQueryList.Resp) {

                                ToastUtils.showToast(UnionTranscationRecordActivity
                                                .this,
                                        baseResp.getMsg() + "，" + baseResp.getCode());
                            }
                        }
                    });
                } catch(ActionIllegalException e) {
                    e.printStackTrace();
                }
            }
        }

    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_union_transcation_record;
    }

    @Override
    protected void initBase() {
        super.initBase();
        ButterKnife.bind(this);
        tvTitle.setText("交易记录");
//        tvRight.setText("清空交易记录");
        tvRight.setVisibility(View.GONE);
        sytApi = SytFactory.createSytIml(this);

        recyclerview.setLayoutManager(new LinearLayoutManager(this,
                LinearLayoutManager.VERTICAL, false));
        DividerItemDecoration divider = new DividerItemDecoration(this,
                DividerItemDecoration.VERTICAL);
        divider.setDrawable(getResources().getDrawable(R.drawable.divider));
        recyclerview.addItemDecoration(divider);
        refreshLayout.setOnRefreshListener(refreshlayout -> refreshlayout.getLayout().postDelayed(() -> {
            curPage = 1;
            getTranscation(curPage);
            refreshlayout.finishRefresh();
        }, 500));
        refreshLayout.setOnLoadmoreListener(refreshlayout -> refreshlayout.getLayout().postDelayed(() -> {
            curPage++;
            getTranscation(curPage);
            refreshlayout.finishLoadmore();

        }, 500));

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.ACTION);
        registerReceiver(broadcastReceive, intentFilter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if(!sdf.format(new Date()).equals(Hawk.get("signTime", "0"))) {
            sign();
        } else {
            curPage = 1;
            getTranscation(curPage);
        }
    }

    private void getTranscation(int page) {
        TransQueryList.Req req = new TransQueryList.Req();
        req.merchantId = Hawk.get("unionMerchantId", "");
        req.pageIndex = page;
        req.pageSize = 50;
        sytApi.sendReq(req);
    }

    private void initData(List<TradeInfo> listTrade) {
        if(listTrade.size() == 0 && curPage == 1) {
            rlNoData.setVisibility(View.VISIBLE);
            recyclerview.setVisibility(View.GONE);
        } else {
            if(listTrade.size() == 0) return;
            if(unionTranscationAdapter == null) {
                unionTranscationAdapter = new UnionTranscationAdapter(this, listTrade);
                recyclerview.setAdapter(unionTranscationAdapter);
            } else {
                if(curPage == 1) {
                    unionTranscationAdapter.updateData(listTrade);
                } else {
                    unionTranscationAdapter.addData(listTrade);
                }
            }

        }
    }

    private void sign() {
        PosSign.Req req = new PosSign.Req();
        sytApi.sendReq(req);
    }

    @OnClick({R.id.img_back, R.id.tv_right, R.id.ib_serach})
    public void onViewClicked(View view) {
        switch(view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.tv_right:
                new AlertDialog.Builder(UnionTranscationRecordActivity.this,
                        R.style.Theme_AppCompat_DayNight_Dialog_Alert)
                        .setTitle("提示")
                        .setMessage("清空POS本地刷卡交易记录？")
                        .setCancelable(false)
                        .setPositiveButton("确定", (dialog, which) -> {
                            finish();
                        })
                        .setNegativeButton("取消", (dialog, which) -> {
                        })
                        .show();
                break;
            case R.id.ib_serach:
//                TradeInfo tradeInfo =
//                        tradeInfoDao.findByReferenceNo(etReferenceNo.getText()
//                        .toString());
//                if(tradeInfo == null) {
//                    showToast("未查到交易订单，请重新输入");
//                } else {
//                    Intent intent = new Intent(UnionTranscationRecordActivity.this,
//                            UnionTranscationDetailActivity.class);
//                    intent.putExtra("tradeInfo", tradeInfo);
//                    startActivity(intent);
//                }
                break;
        }
    }

    @Override
    public void onDestroy() {
        try {
            unregisterReceiver(broadcastReceive);
        } catch(Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }
}
